package server;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import com.google.gdata.client.GoogleService;
import com.google.gdata.data.Category;
import com.google.gdata.data.Entry;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.ServiceException;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import controller.Utils;

import data.Data;

public class PostBlogger {
	public static void postBlogger(String title,String description,ArrayList<String> tag,DBObject users,String cate) throws IOException, ServiceException
	{

		if(users != null)
		{
			
			String keyword = "";
		    
			if(!cate.equals(""))
			{
				keyword=cate;
			} else {
			    if(tag.size() > 0)
			    {
			    	for (int i = 0; i < tag.size(); i++) {
			    		if(keyword.equals(""))
			    		{
			    			keyword = tag.get(i);
			    		} else {
			    			keyword += ","+tag.get(i);
			    		}
			    			
					}
			    }
			}
		    Entry myEntry = new Entry();
			GoogleService myService = new GoogleService("blogger", "exampleCo-exampleApp-1");
			myService.setUserCredentials(users.get("email").toString(), users.get("passwordemail").toString());
			
			if(!keyword.equals(""))
			{
				Category category = new Category();
				category.setScheme("http://www.blogger.com/atom/ns#");
				category.setTerm(Utils.convertNCR(keyword));
				myEntry.getCategories().add(category);
			}
			myEntry.setTitle(new PlainTextConstruct(title));
			myEntry.setContent(new PlainTextConstruct(description.replaceAll("\\n", "")));
			
			// Ask the service to insert the new entry
			URL postUrl = new URL("http://www.blogger.com/feeds/"+users.get("blogid")+"/posts/default");
			myService.insert(postUrl, myEntry);
		}
	}
}
